package cn.airfei.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @description:
 * @author: air
 * @create: 2019-10-17 17:22
 **/
public class WSServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {

        ChannelPipeline channelPipeline = ch.pipeline();
        // websocket 基于http协议,故需要有http编解码器
        channelPipeline.addLast(new HttpServerCodec());
        // 支持大数据流
        channelPipeline.addLast(new ChunkedWriteHandler());

        // 对httpMessage 进行聚合成FullHttpRequest Or FullHttpResponse
        channelPipeline.addLast(new HttpObjectAggregator(1024 * 64));

        // *******以上用于支持http协议 *****************//


        // websocket 服务处理协议， 用于指定给客户端链接访问的路由： /ws
        // WebSocketServerProtocolHandler 会处理复杂的事,如握手动作等(control frames (Close, Ping, Pong))
        // 都是已frames进行传输的
        channelPipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

        // 自定义handler
        channelPipeline.addLast(new ChatHandler());

    }
}
